package com.yxhl.zoume.core.func.pay.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding.view.RxView;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.zoume.PaymentFragmentDataBinding;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.ui.fragment.BaseDataBindingFragment;
import com.yxhl.zoume.core.func.pay.activity.BusPaymentActivity;
import com.yxhl.zoume.core.func.pay.model.BusPaymentEnum;
import com.yxhl.zoume.core.func.pay.presenter.AliPayPresenter;
import com.yxhl.zoume.core.func.pay.presenter.WalletPayPresenter;
import com.yxhl.zoume.core.func.pay.presenter.WeChatPayPresenter;
import com.yxhl.zoume.core.func.pay.view.AliPayView;
import com.yxhl.zoume.core.func.pay.view.WalletPayView;
import com.yxhl.zoume.core.func.pay.view.WeChatPayView;
import com.yxhl.zoume.core.main.info.MainEntrance;
import com.yxhl.zoume.core.main.model.MainEntranceInfo;
import com.yxhl.zoume.data.http.model.busticket.ZMBusTicketOrder;
import com.yxhl.zoume.di.component.pay.OrderPayComponent;
import com.yxhl.zoume.utils.PromptUtils;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * 订单支付页面
 * 负责订单展示与支付逻辑
 * Created by vhawk on 16/3/31.
 */
public class BusPaymentFragment extends BaseDataBindingFragment implements AliPayView, WeChatPayView, WalletPayView {
    private static final String EXTRA_PAYMENT_ZOUME_BUS_ORDER = "extra_payment_zoume_bus_order";
    private static final String EXTRA_PAYMENT_TICKET_BUS_ORDER = "extra_payment_bus_ticket_order";
    /**
     * 支付宝支付presenter
     */
    @Inject
    public AliPayPresenter aliPayPresenter;
    /**
     * 微信支付presenter
     */
    @Inject
    public WeChatPayPresenter weChatPayPresenter;

    @Inject
    public WalletPayPresenter walletPayPresenter;

    @BindView(R.id.rl_wallet_pay)
    RelativeLayout walletPayRl;
    @BindView(R.id.rl_wechat_pay)
    RelativeLayout wechatPayRl;
    @BindView(R.id.rl_ali_pay)
    RelativeLayout aliPayRl;
    /**
     * 出发车站
     */
    @BindView(R.id.start_city_textview)
    TextView startCityTextView;
    /**
     * 乘车日期
     */
    @BindView(R.id.trip_date_textview)
    TextView tripDateTextView;
    /**
     * 乘车时间
     */
    @BindView(R.id.trip_time_textview)
    TextView tripTimeTextView;
    /**
     * 到达城市
     */
    @BindView(R.id.arrival_city_textview)
    TextView arrivalCityTextView;
    /**
     * 定制巴士头部下方布局
     */
    @BindView(R.id.zoume_bus_order_header_layout)
    RelativeLayout zouMeBusOrderHeaderLayout;
    // 车型
    @BindView(R.id.bus_type_textview)
    TextView zouMeBusOrderBusTypeTextView;
    // 单价
    @BindView(R.id.bus_ticket_price_textview)
    TextView zouMeBusOrderUnitPriceTextView;

    // 乘车人数
    @BindView(R.id.number_of_passengers_textview)
    TextView zouMeBusOrderNumberOfPsgersTextView;
    // 是否接驳
    @BindView(R.id.is_need_shuttle_textview)
    TextView zouMeBusOrderIsNeedShuttleTextView;

    /**
     * 总价:￥99.00
     */
    @BindView(R.id.total_amount_textview)
    TextView mTotalAmountTextView;

    /**
     * 向上箭头
     */
    @BindView(R.id.iv_icon_up_arrow)
    ImageView mUpArrow;
    /**
     * 去支付按钮
     */
    @BindView(R.id.pay_confirm_textview)
    TextView payConfirmTextView;
    /**
     * 巴士车票
     */
    ZMBusTicketOrder mBusTicketOrder;
    /**
     * 定制巴士、固定时刻类巴士
     */
    BizOrder mCurrentOrder;
    MaterialDialog dialogForWaitingPayment;
    private OrderPayComponent component;
    private PaymentFragmentDataBinding paymentFragmentDataBinding;

    public static BusPaymentFragment newInstance(BizOrder order) {
        BusPaymentFragment fragment = new BusPaymentFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_PAYMENT_ZOUME_BUS_ORDER, order);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static BusPaymentFragment newInstance(ZMBusTicketOrder order) {
        BusPaymentFragment fragment = new BusPaymentFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_PAYMENT_TICKET_BUS_ORDER, order);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 获取携带过来的数据
     * 用以初始化界面以及发送网络请求
     */
    private void parseArguments() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            // 定制巴士、固定时刻类巴士
            mCurrentOrder = (BizOrder) bundle.getSerializable(EXTRA_PAYMENT_ZOUME_BUS_ORDER);
            // 巴士车票
            mBusTicketOrder = (ZMBusTicketOrder) bundle.getSerializable(EXTRA_PAYMENT_TICKET_BUS_ORDER);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parseArguments();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        initializeDisplay();
        aliPayPresenter.attachView(this);
        weChatPayPresenter.attachView(this);
        walletPayPresenter.attachView(this);
        paymentFragmentDataBinding.setBusPaymentEnum(BusPaymentEnum.BUS_PAYMENT_ENUM_WECHAT);
        onClickEvent();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        aliPayPresenter.onResume();
        weChatPayPresenter.onResume();
        walletPayPresenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        aliPayPresenter.onResume();
        weChatPayPresenter.onResume();
        walletPayPresenter.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        aliPayPresenter.onDestroy();
        weChatPayPresenter.onDestroy();
        walletPayPresenter.onDestroy();
    }


    private void onClickEvent() {

        RxView.clicks(walletPayRl).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                paymentFragmentDataBinding.setBusPaymentEnum(BusPaymentEnum.BUS_PAYMENT_ENUM_WALLET);
            }
        });

        RxView.clicks(wechatPayRl).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                paymentFragmentDataBinding.setBusPaymentEnum(BusPaymentEnum.BUS_PAYMENT_ENUM_WECHAT);
            }
        });

        RxView.clicks(aliPayRl).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                paymentFragmentDataBinding.setBusPaymentEnum(BusPaymentEnum.BUS_PAYMENT_ENUM_ALI);
            }
        });
    }

    /**
     * 初始化显示
     */
    private void initializeDisplay() {
        if (null != mCurrentOrder) {
            exchangeUI(mCurrentOrder);
            bindData(mCurrentOrder);
        } else {
            if (null != mBusTicketOrder) {
                exchangeUI();
                bindData(mBusTicketOrder);
            }
        }
    }

    /**
     * 在巴士模块售票下,非定制巴士订单详情转支付页面
     */
    private void exchangeUI() {
        // 隐藏底部向上箭头
        mUpArrow.setVisibility(View.GONE);
        zouMeBusOrderHeaderLayout.setVisibility(View.GONE);
    }

    private void exchangeUI(BizOrder order) {
        // 隐藏底部向上箭头
        mUpArrow.setVisibility(View.GONE);

        OrderBizType bizType = order.getBizType();
        switch (bizType) {
            case TICKET:
            case OBT_FT_BUS:
            case OBT_DABA_TICKET:
                zouMeBusOrderHeaderLayout.setVisibility(View.GONE);
                break;
            case OBT_DIY_BUS:
                zouMeBusOrderBusTypeTextView.setText(getString(R.string.zoume_bus_model));
                zouMeBusOrderUnitPriceTextView.setText(order.getPrice() + "元");

                zouMeBusOrderNumberOfPsgersTextView.setText(order.getAmount() + "");
                zouMeBusOrderIsNeedShuttleTextView.setText(order.getNdFerry() ? "是" : "否");
                break;
        }
    }

    /**
     * 绑定数据
     *
     * @param order
     */
    private void bindData(BizOrder order) {
        startCityTextView.setText(order.getStart());
        String[] dateAndTime = order.getGmtDepart().split(" ");
        tripTimeTextView.setText(dateAndTime[0]);
        tripDateTextView.setText(dateAndTime[1]);
        arrivalCityTextView.setText(order.getDestination());

        mTotalAmountTextView.setText(" " + String.valueOf(order.getTotalFee()) + "元");
        zouMeBusOrderNumberOfPsgersTextView.setText(order.getAmount() + "");
    }

    /**
     * 绑定数据
     *
     * @param busTicketOrder
     */
    private void bindData(ZMBusTicketOrder busTicketOrder) {
        // 出发站-出行日期和时间-到达站
        startCityTextView.setText(busTicketOrder.getStartCityName());
        tripTimeTextView.setText(busTicketOrder.getDepartTime());
        tripDateTextView.setText(busTicketOrder.getDepartDate());
        arrivalCityTextView.setText(busTicketOrder.getArrivalStationName());

        // 总价 99.00
        mTotalAmountTextView.setText("¥" + busTicketOrder.getTicketPrice());
        // 乘客人数 (5人)
        zouMeBusOrderNumberOfPsgersTextView.setText(busTicketOrder.getPassengerCount() + "");
    }

    /**
     * 点击支付按钮, 订单支付处理
     */
    @OnClick(R.id.pay_confirm_textview)
    public void onPayConfirmClick() {
        // 微信需要 等待loading
        switch (paymentFragmentDataBinding.getBusPaymentEnum()) {
            case BUS_PAYMENT_ENUM_WALLET:
                if (mCurrentOrder == null) {
                    payByWallet(mBusTicketOrder.getOrderId());
                } else {
                    payByWallet(mCurrentOrder.getOrderSerial());
                }
                break;
            case BUS_PAYMENT_ENUM_WECHAT:
                waitingForPayment(true);
                if (mCurrentOrder == null) {
                    payByWeChat(mBusTicketOrder.getOrderId());
                } else {
                    payByWeChat(mCurrentOrder.getOrderSerial());
                }
                break;
            case BUS_PAYMENT_ENUM_ALI:
                if (mCurrentOrder == null) {
                    payByAli(mBusTicketOrder.getTotalFee(), String.valueOf(mBusTicketOrder.getOrderId()));
                } else {
                    payByAli(String.valueOf(mCurrentOrder.getTotalFee()), mCurrentOrder.getOrderSerial());
                }
                break;
        }
    }

    /**
     * 钱包支付
     */
    private void payByWallet(String orderId) {
        walletPayPresenter.payByWallet(orderId);
    }

    /**
     * 通过微信渠道完成支付
     *
     * @param ticketOrderId 订单编号
     */
    private void payByWeChat(String ticketOrderId) {
        weChatPayPresenter.getWeChatPayOrderInfo(component.context(), ticketOrderId);
    }

    /**
     * 通过支付宝渠道完成支付
     *
     * @param totalFee      支付费用
     * @param ticketOrderId 订单编号
     */
    private void payByAli(String totalFee, String ticketOrderId) {
        aliPayPresenter.getSignedStr(component.context(), totalFee, ticketOrderId);
    }

    @Override
    protected View getContentLayout(LayoutInflater inflater, ViewGroup container) {
        paymentFragmentDataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_order_pay, container, false);
        return paymentFragmentDataBinding.getRoot();
    }

    @Override
    protected void setupToolBar() {
        if (getActivity() instanceof BusPaymentActivity) {
            ((BusPaymentActivity) getActivity()).setToolbarTitle(getString(R.string.title_payment_confirm));
        }
    }

    @Override
    public void handleWalletPaySucceed() {
        PromptUtils.showShort(component.context(), "支付成功");
        paySucceed();
    }

    @Override
    public void handleWalletPayFailure(String msg) {
        PromptUtils.showShort(mActivity, msg);
    }

    @Override
    public void handleWalletPayError() {
        PromptUtils.showShort(mActivity, R.string.net_error);
    }

    @Override
    public void renderAliPaySucceed() {
        paySucceed();
    }

    @Override
    public void renderAliPayFailure(String resultStatus) {
        paySucceed();
    }

    @Override
    public void renderAliPaySignedError() {
        PromptUtils.showShort(mActivity, getString(R.string.ali_payment_error));
        waitingForPayment(false);
    }

    private void paySucceed() {
        getAppComponent().navigator().navigateToMain(getActivity(), new MainEntranceInfo(MainEntrance.PAYMENT));
    }

    /**
     * 等待支付
     *
     * @param isWaiting
     */
    public void waitingForPayment(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingPayment = new MaterialDialog.Builder(component.context())
                    .content(R.string.dialog_waiting_paying)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            if (null != dialogForWaitingPayment) {
                dialogForWaitingPayment.dismiss();
            }
        }
    }

    @Override
    public void dismissWaitingDialog() {
        waitingForPayment(false);
    }

    @Override
    public void showErrorMessage(String errorMessage) {
        waitingForPayment(false);
        PromptUtils.showShort(component.context(), errorMessage);
    }

    @Override
    public void showWechatUninstalledDialog() {
        waitingForPayment(false);

        new MaterialDialog.Builder(component.context())
                .content(R.string.hint_wechat_uninstalled)
                .positiveText(R.string.dialog_confirm)
                .positiveColorRes(R.color.app_primary_blue)
                .canceledOnTouchOutside(false)
                .show();

        new MaterialDialog.Builder(component.context())
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                });
    }

    @Override
    protected void initializeInjector() {
        component = getComponent(OrderPayComponent.class);
        component.inject(this);
    }
}
